/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chanceit.ssss.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.http.AjaxCallBack;

import org.gl.GlobalVariable;
import org.gl.customview.PullToRefreshView;
import org.gl.customview.PullToRefreshView.OnFooterRefreshListener;
import org.gl.customview.PullToRefreshView.OnHeaderRefreshListener;
import org.gl.utils.lg;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.chanceit.ssss.activity.R;
import com.chanceit.ssss.common.ActivityActionName;
import com.chanceit.ssss.common.IntentExtraDataKey;

/**
 * the all carder list that has ordered and state is 0.
 * 
 * @author Administrator
 * 
 */
public class TodoComplaintListFragment extends BaseFragment implements
		OnItemClickListener,OnHeaderRefreshListener, OnFooterRefreshListener {
	OnListFragmentSelectedListener mCallback;
	List<Map<String, Object>> contents = new ArrayList<Map<String, Object>>();
//	String[] keys = new String[] { "userName", "title", "applyTime", "handler",
//			"handleTime", "complaintId" };
	String[] keys = new String[] { "title", "", "",
			"applyTime", "state","complaintId" };
	protected JSONArray userListJosnAry = new JSONArray();
	SimpleAdapter adapter;
	int page =1;
	// The container Activity must implement this interface so the frag can
	// deliver messages
	public interface OnListFragmentSelectedListener {
		/** Called by HeadlinesFragment when a list item is selected */
		public void onArticleSelected(int position);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	ListView listView;
	PullToRefreshView mPullToRefreshView;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.todo_list, container, false);
		listView = (ListView) view.findViewById(R.id.order_carer_lv);
		listView.setOnItemClickListener(this);
		mPullToRefreshView = (PullToRefreshView) (view
				.findViewById(R.id.main_pull_refresh_view));
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		((TextView)view.findViewById(R.id.tv_title_tv_content)).setText(getString(R.string.title_com_todo_list));
		initData();
		return view;
	}

	private void initData() {
		if (adapter != null && userListJosnAry != null
				&& userListJosnAry.length() > 0) {
			setListAdapter(adapter);
			lg.i(TAG, "resotre the fragment");
			return;
		}
		getdata(null);

	}

	private void getdata(Integer _page) {
		ds.getComplaintList(_page, null, null, null, null, "0",
				null,
				new AjaxCallBack<String>() {
					@Override
					public void onStart() {
						super.onStart();
						loading();
					}

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						super.onFailure(t, errorNo, strMsg);
						loadFailed(strMsg);
					}

					public void onSuccess(String t) {
						lg.i(TAG, t);
						int code = 0;
						String mesage = "";
						if (getActivity()==null) {
							return;
						}
						try {
							JSONObject result = new JSONObject(t);
							code = result.optInt(webkey.code);
							mesage = result.optString(webkey.reason);
							
							JSONArray newJsonArray = result
									.optJSONArray(webkey.result);
							contents.removeAll(contents);
							if (page<=1) {//如果当前页码为<=1 说明是第一次加载 清楚以前的旧数据
								userListJosnAry = null;
								userListJosnAry=newJsonArray;
							}else{//否则就是加载更多的分页数据,把新的数据添加到集合中
								for (int i = 0; i < newJsonArray.length(); i++) {
									userListJosnAry.put(newJsonArray.opt(i));
								}
							}
							if (userListJosnAry == null) {
								userListJosnAry = new JSONArray();
							}
							int count = userListJosnAry.length();
							for (int i = 0; i < count; i++) {
								Map<String, Object> map = new HashMap<String, Object>();
								JSONObject temp = userListJosnAry
										.getJSONObject(i);
								for (String key : keys) {
									Object o = temp.opt(key);
									if (o == null) {
										o = "";
									}
									if (key.toString().equals("state")) {
										if (o.toString().equals("0")) {
											map.put(key, R.drawable.complain_type_w);
										} else if (o.toString().equals("1")) {
											map.put(key, R.drawable.complain_type_y);
										} else if (o.toString().equals("2")){
											map.put(key, R.drawable.complain_type_yq);
										}
									} else {
										map.put(key, o.toString());
									}
								}
								contents.add(map);
							}
							if (adapter==null) {
								if (contents.size()>0) {
									adapter = new SimpleAdapter(getActivity(),
											(List<Map<String, Object>>) contents,
											R.layout.list_item_com, keys, new int[] {
													R.id.textView1, R.id.textView2, R.id.textView3,
													R.id.textView4, R.id.textView5 });
									setListAdapter(adapter);
								}
							}else{
								adapter.notifyDataSetChanged();
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} finally {
							page--;
							if (code != 0) {
								loadFailed(mesage);
							} else {
								loadSuccessed();
								page++;
							}
						}

					}
				});
	}

	protected void setListAdapter(SimpleAdapter adapter) {
		if (listView != null && adapter != null) {
			listView.setAdapter(adapter);
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
			listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// This makes sure that the container activity has implemented
		// the callback interface. If not, it throws an exception.
		try {
			mCallback = (OnListFragmentSelectedListener) activity;
		} catch (ClassCastException e) {
			lg.e(TAG,
					"this activity not implents OnListFragmentSelectedListener");
		}
	}

	@Override
	public void onItemClick(AdapterView<?> l, View v, int position, long id) {
		if (mCallback != null) {
			mCallback.onArticleSelected(position);
		}
		// getListView().setItemChecked(position, true);
		try {
			GlobalVariable.getGlobalInstance().intent.putExtra(
					IntentExtraDataKey.MESSAGE_INFO_ID,
					userListJosnAry.getJSONObject(position).optInt(
							IntentExtraDataKey.COMPLAINTID));
			GlobalVariable.getGlobalInstance().intent.putExtra(
					IntentExtraDataKey.MESSAGE_INFO_TYPE,
					IntentExtraDataKey.COMPLAINTID);
			startActivity(GlobalVariable.getGlobalInstance().intent
					.setAction(ActivityActionName.MESSAGEINFO));
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
			Toast.makeText(getActivity(), "null RESERVEID", Toast.LENGTH_SHORT)
					.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {

				page++;
				getdata(page);
				mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1000);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
				page = 1;
				getdata(page);
				// 设置更新时间
				// mPullToRefreshView.onHeaderRefreshComplete("最近更新:01-23 12:01");
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1000);

	}
}